<template>
  <div class="view-register">
    <div class="logo">
      <img src="../assets/img/other/keTangLogo.png" alt="ha" @click="jumpToBigPage">
    </div>
    <div class="register-content">
      <div class="left">
        <img src="../assets/img/other/register.png" alt="">
      </div>
      <div class="right">
        <div class="right-content">
          <h2 class="title">
            注册账号
          </h2>
          <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
                   class="demo-ruleForm">
            <el-form-item prop="phone">
              <el-input v-model="ruleForm.phone" placeholder="请输入邮箱/手机号"></el-input>
            </el-form-item>
            <el-form-item prop="pass">
              <el-input type="password" v-model="ruleForm.pass" autocomplete="off" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item prop="checkPass">
              <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"
                        placeholder="请再次输入密码确认"></el-input>
            </el-form-item>
          </el-form>
          <div class="choice">
            <p class="identity">选择身份</p>
            <div class="role">
              <div class="item" :class="{active: role === 'teacher'}" @click="changeRole('teacher')">
                <img src="../assets/img/other/teacherimg.png" alt="ha">
                <span>老师</span>
              </div>
              <div class="item" :class="{active: role === 'student'}" @click="changeRole('student')">
                <img src="../assets/img/other/studentimg.png" alt="ha">
                <span>学生</span>
              </div>
            </div>
          </div>
          <div class="teacher" v-show="role === 'teacher'">
            <el-form :model="ruleForm1" status-icon :rules="rules1" ref="ruleForm1" label-width="100px"
                     class="demo-ruleForm">
              <el-form-item prop="name">
                <el-input v-model="ruleForm1.name" placeholder="请输入姓名"></el-input>
              </el-form-item>
              <el-form-item prop="school">
                <el-input type="text" v-model="ruleForm1.school" autocomplete="off"
                          placeholder="请输入学校/机构"></el-input>
              </el-form-item>
              <div class="code">
                <el-form-item prop="code">
                  <el-input v-model="ruleForm1.code" autocomplete="off" placeholder="请输入验证码"></el-input>
                </el-form-item>
                <div style="cursor:pointer;" @click="changeCode">
                  <img :src="imgUrl[0]" alt="ha" class="code-img">
                  <div class="code-number">
                    <p :style="{color:number1Color}"> {{ number1 }}</p>
                    <p :style="{color:operatorColor}"> {{ operator }}</p>
                    <p :style="{color:number2Color}"> {{ number2 }} = </p>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
          <div class="student" v-show="role === 'student'">
            <el-form :model="ruleForm2" status-icon :rules="rules2" ref="ruleForm2" label-width="100px"
                     class="demo-ruleForm">
              <el-form-item prop="name">
                <el-input type="text" v-model="ruleForm2.name" autocomplete="off" placeholder="请输入姓名"></el-input>
              </el-form-item>
              <el-form-item prop="school">
                <el-input type="text" v-model="ruleForm2.school" autocomplete="off"
                          placeholder="请输入学校/机构"></el-input>
              </el-form-item>
              <el-form-item prop="studentNumber">
                <el-input v-model="ruleForm2.studentNumber" placeholder="请输入学号"></el-input>
              </el-form-item>
              <div class="code">
                <el-form-item prop="code">
                  <el-input v-model="ruleForm2.code" autocomplete="off" placeholder="请输入验证码"></el-input>
                </el-form-item>
                <div style="cursor:pointer;" @click="changeCode">
                  <img :src="imgUrl[0]" alt="ha" class="code-img">
                  <div class="code-number1">
                    <p :style="{color:number1Color}"> {{ number1 }}</p>
                    <p :style="{color:operatorColor}"> {{ operator }}</p>
                    <p :style="{color:number2Color}"> {{ number2 }} = </p>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
          <div class="register-button">
            <el-button type="primary" class="main" @click="register('ruleForm2')">注册</el-button>
            <div class="login">
              <p>已有账号？
                <span @click="jumpToLog">去登录</span>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  data() {
    const judgePhone = new RegExp(/^\d{11}$/);
    const judgeEmail = new RegExp(/^[\w.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/);
    const judgePassword = new RegExp(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{2,64}$/);
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号/邮箱不能为空'));
      }
      setTimeout(() => {
        if (judgeEmail.test(value) || judgePhone.test(value)) {
          callback();
        } else {
          callback(new Error('格式不正确'))
        }
      }, 1000);
    };
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (!judgePassword.test(value)) {
        callback(new Error('输入密码的格式不正确'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
    const checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('验证码不能为空'));
      }
      setTimeout(() => {
        if (value !== this.result().toString()) {
          callback(new Error('验证码输入错误'));
        } else {
          callback();
        }
      }, 1000);

    }
    const checkName = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入姓名'));
      } else {
        callback()
      }
    };
    const validateSchool = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入学校'));
      } else {
        callback()
      }
    };
    const checkNumber = (rule, value, callback) => {

      if (!value) {
        return callback(new Error('学号不能为空'));
      }
      setTimeout(() => {
        if (!judgePhone.test(value)) {
          callback(new Error('请输入11位的数字学号'));
        } else {
          callback()
        }
      }, 1000);
    };

    return {
      judgeForm1: false,
      judgeForm2: false,
      number1: '0',
      number2: '0',
      operator: '',
      number1Color: 'red',
      number2Color: 'red',
      operatorColor: 'red',
      imgUrl: ['https://tse1-mm.cn.bing.net/th/id/OIP-C.Vk0v8U2xA-xx9H3min6SQgHaEK?w=257&h=180&c=7&r=0&o=5&pid=1.7',
        'https://tse1-mm.cn.bing.net/th/id/OIP-C.zQczl4fN1AgYr9Fi7IhoOAHaEo?w=264&h=180&c=7&r=0&o=5&pid=1.7'],
      ruleForm1: {
        school: '',
        name: '',
        code: ''
      },
      ruleForm: {
        pass: '',
        checkPass: '',
        phone: ''
      },
      ruleForm2: {
        name: '',
        school: '',
        studentNumber: '',
        code: ''
      },
      rules: {
        pass: [
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          {validator: validatePass2, trigger: 'blur'}
        ],
        phone: [
          {validator: checkPhone, trigger: 'blur'}
        ]
      },
      rules1: {
        school: [
          {validator: validateSchool, trigger: 'blur'}
        ],
        name: [
          {validator: checkName, trigger: 'blur'}
        ],
        code: [
          {validator: checkCode, trigger: "blur"}
        ]
      },

      rules2: {
        name: [
          {validator: checkName, trigger: 'blur'}
        ],
        school: [
          {validator: validateSchool, trigger: 'blur'}
        ],
        studentNumber: [
          {validator: checkNumber, trigger: 'blur'}
        ],
        code: [
          {validator: checkCode, trigger: 'blur'}
        ]
      },
      role: "teacher"
    }
  },
  components: {},
  methods: {
    jumpToLog() {
      this.$router.push('/login')
    },
    changeRole(role) {
      this.role = role
    },
    generateNumbers() {
      this.number1 = Math.ceil(Math.random() * 10);
      this.number2 = Math.ceil(Math.random() * 10);
    },
    generateOperate() {
      let a = Math.ceil(Math.random() * 3)
      switch (a) {
        case 1:
          this.operator = '+';
          break;
        case 2:
          this.operator = '-';
          break;
        case 3:
          this.operator = '*';
          break;
      }
    },
    getRandomColor() {
      const letters = "0123456789ABCDEF";
      let color = "#";
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    },
    changeCode() {
      this.generateNumbers()
      this.generateOperate()
      this.number1Color = this.getRandomColor()
      this.number2Color = this.getRandomColor()
      this.operatorColor = this.getRandomColor()
    },
    result() {
      switch (this.operator) {
        case '+':
          return this.number1 + this.number2;
        case '-':
          return this.number1 - this.number2;
        case '*':
          return this.number1 * this.number2;
      }
    },
    register() {
      if (this.role === 'teacher') {
        this.validateTwoForm('ruleForm', 'ruleForm1');
        if (this.judgeForm1 && this.judgeForm2) {
          this.request.post('/registerTeacher', {
            phone: this.ruleForm.phone,
            password: this.$md5(this.ruleForm.pass),
            name: this.ruleForm1.name,
            school: this.ruleForm1.school
          }).then(res => {
            if (res === 'The user has been registered') {
              this.$message.error("用户已被注册")
            } else if (res === 'User registration succeeded') {
              this.tip()
            } else if (res === 'Phone is error') {
              this.$message.error('邮箱格式不正确')
            }
          })
        }
      } else if (this.role === 'student') {
        this.validateTwoForm('ruleForm', 'ruleForm2')
        if (this.judgeForm1 && this.judgeForm2) {
          this.request.post('/registerStudent', {
            phone: this.ruleForm.phone,
            password: this.$md5(this.ruleForm.pass),
            name: this.ruleForm2.name,
            school: this.ruleForm2.school,
            studentId: this.ruleForm2.studentNumber
          }).then(res => {
            if (res === 'The user has been registered') {
              this.$message.error("用户已被注册")
            } else if (res === 'User registration succeeded') {
              this.tip()
            } else if (res === 'Phone is error') {
              this.$message.error('邮箱格式不正确')
            }
          })
        }
      }
    },
    validateTwoForm(ruleForm1, ruleForm2) {
      this.$refs[ruleForm1].validate(valid => {
        if (valid) {
          this.judgeForm1 = true
        } else {
          this.judgeForm1 = false
        }
      })
      this.$refs[ruleForm2].validate(valid => {
        if (valid) {
          this.judgeForm2 = true
        } else {
          this.judgeForm2 = false
        }
      })
    },
    tip() {
      this.$confirm('是否跳转登录页面？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$router.push("/main")
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消跳转'
        });
      });
    },
    jumpToBigPage(){
      this.$router.push("/bigPage/homePage")
    }
  },

  mounted() {
    this.generateNumbers()
    this.generateOperate()
    this.number1Color = this.getRandomColor()
    this.number2Color = this.getRandomColor()
    this.operatorColor = this.getRandomColor()
  }
}


</script>

<style scoped>
.view-register {
  background-size: 100%;
  position: relative;
  width: 100%;
  background: #f8f9fa no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  min-height: calc(100vh);
}

.logo {
  position: absolute;
  top: 70px;
  left: 90px;
  cursor: pointer;
}

.logo img {
  display: block;
  max-width: 180px;
  max-height: 45px;
}

.register-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.left {
  margin-right: -100px;
}

.left img {
  display: block;
  height: 660px;
}

.right {
  margin: 12px 0;
}

.right-content {
  width: 540px;
  padding: 0 40px;
  background: #fff;
  border: 1px solid #eee;
  box-shadow: 0 0 61px 0 rgba(85, 108, 144, .07);
}

.title {
  position: relative;
  padding: 27px 0;
  text-align: center;
  font-size: 30px;
  font-weight: 700;
}

.choice {
  line-height: 50px;
  position: relative;
  font-size: 14px;
}

.identity {
  font-size: 22px;
  font-weight: 600;
}

.role {
  display: flex;
  justify-content: space-between;
}

.item {
  display: flex;
  align-items: center;
  width: 210px;
  padding: 10px 16px;
  border: 1px solid #fff;
}

.item img {
  margin-right: 9px;
  display: block;
  width: 54px;
  height: 54px;
  border-radius: 50%;
}

.item span {
  font-size: 20px;
  font-family: MicrosoftYaHei;
  text-align: center;
  color: #3c4043;
  line-height: 24px;
  letter-spacing: 1px;
}

.register-button {
  padding-bottom: 20px;
  margin-top: 2px;
}

.main {
  width: 100%;
  height: 60px;
}

.el-button {
  font-size: 20px;
}

.login {
  margin-top: 30px;
}

.login p {
  display: flex;
  justify-content: flex-end;
  font-size: 20px;
}

.login span {
  cursor: pointer;
  color: #4285f4;
}

.active {
  border: 1px solid #4285f4;
}

.el-form {
  transform: translateX(-100px);
}

::v-deep .el-input__inner {
  font-size: 20px;
  height: 60px;
}

::v-deep .el-input {
  width: 128%;
}

::v-deep .el-form-item__error {
  font-size: 17px;
}

::v-deep .el-form-item {
  margin-bottom: 23px;
}

.teacher {
  margin-top: 25px;
}

.student {
  margin-top: 30px;
}

.code {
  width: 545px;
  display: flex;
  justify-content: space-between;
}

.code-img {
  cursor: pointer;
  display: block;
  border-radius: 8px;
  margin-left: 80px;
  width: 232px;
  height: 60px;
}

.code-number {
  top: 167px;
  display: flex;
  position: absolute;
  right: -50px;
  font-size: 45px;
}

.code-number1 {
  top: 248px;
  display: flex;
  position: absolute;
  right: -50px;
  font-size: 45px;
}

.code-number p {
  margin-left: 10px;
}

.code-number1 p {
  margin-left: 10px;
}

::v-deep .el-message-box__headerbtn {
  top: 10px;
  right: 10px;
  font-size: 25px;
}

::v-deep .el-message-box__status {
  font-size: 30px !important;
  transform: translateY(1px);
  padding-right: 8px;
}

::v-deep .el-message-box__content {
  font-size: 20px;
  padding: 20px 15px;
}

::v-deep .el-button--small {
  font-size: 20px;
}

::v-deep .el-message-box__btns button:nth-child(2) {
  margin-left: 30px;
}
</style>
